using System;
using System.Windows.Forms;
using Nuwanda.TfsSpotlight.Shell.Exceptions;
using Nuwanda.TfsSpotlight.Shell.Proxies.Interfaces;
using Nuwanda.TfsSpotlight.Shell.Services;

namespace Nuwanda.TfsSpotlight.Shell.Expressions
{
    internal class ToolStripConfigurationExpression : IToolStripConfigurationExpression
    {
        private readonly IMenuState _state;
        private readonly IToolStrip _toolStrip;
        private TextImageRelation _textImageRelation;
        private ToolStripItemDisplayStyle _displayStyle;

        public ToolStripConfigurationExpression(IMenuState state, IToolStrip toolStrip)
        {
            this._state = state;
            this._toolStrip = toolStrip;
            this._toolStrip.Clear();
            this._textImageRelation = TextImageRelation.ImageAboveText;
            this._displayStyle = ToolStripItemDisplayStyle.ImageAndText;
        }

        public IToolStripConfigurationExpression Composition(TextImageRelation composition)
        {
            this._textImageRelation = composition;
            return this;
        }

        public IToolStripConfigurationExpression Style(ToolStripItemDisplayStyle style)
        {
            this._displayStyle = style;
            return this;
        }

        public IToolStripConfigurationExpression AlignRight(string commandName)
        {
            AddCommandItem(commandName, ToolStripItemAlignment.Right);
            return this;
        }

        public IToolStripConfigurationExpression AlignLeft(string commandName)
        {
            AddCommandItem(commandName, ToolStripItemAlignment.Left);
            return this;
        }

        public IToolStripConfigurationExpression AddLeftSeparator()
        {
            this._toolStrip.Add(new ToolStripSeparator { Alignment = ToolStripItemAlignment.Left });

            return this;
        }

        public IToolStripConfigurationExpression AddRightSeparator()
        {
            this._toolStrip.Add(new ToolStripSeparator { Alignment = ToolStripItemAlignment.Right });

            return this;
        }

        private void AddCommandItem(string commandName, ToolStripItemAlignment alignment)
        {
            if (this._state.Contains(commandName) == false)
                throw new MenuConfigurationException(String.Format("There is no '{0}' command registered.", commandName));

            var commmandConfiguration = this._state[commandName];
            var item = commmandConfiguration.ToToolStripItem();
            item.Alignment = alignment;
            item.TextImageRelation = this._textImageRelation;
            item.DisplayStyle = this._displayStyle;

            this._toolStrip.Add(item);
            commmandConfiguration.ToolStrip = this._toolStrip;
            this._toolStrip.Visible = true;
        }
    }
}